import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@/common/config/config.service';
import { JwtPayload } from '../dto/jwt-payload.dto';
import { UserIdentity } from '../dto/user-identity.dto';
import { UsersService } from '@/modules/users/services/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly config: ConfigService,
    private readonly userService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: config.authSecret,
    });
  }

  async validate(payload: JwtPayload): Promise<UserIdentity> {
    const user = await this.userService.findOne({ id: Number(payload.sub) });
    return { id: user.id, roles: user.roles };
  }
}
